/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Tablespace;
import modelo.conexion.RecolectorDatos;
import modelo.persistencia.XML;
import modelo.respaldo.Respaldo;

/**
 *
 * @author Andrés
 */
public class VistaSeleccionRespaldo extends javax.swing.JFrame {

    /**
     * Creates new form VistaCreacionRespaldo
     */
    private DefaultTableModel defaultTableModel;
    private VistaSeleccionDiaAlMes seleccionDiaAlMes;
    private VistaSeleccionDiaEspecifico seleccionDiaEspecifico;
    private VistaPrincipalRespaldos principal;
    private ArrayList<Tablespace> tablespaces;
    private int regularidad;
    private int tipo;
    private int qTables;
    private RecolectorDatos recolectorDatos;
    private XML objXML;

    private ArrayList<Respaldo> respaldos;

    public VistaSeleccionDiaAlMes getSeleccionDiaAlMes() {
        return seleccionDiaAlMes;
    }

    public void setPrincipal(VistaPrincipalRespaldos principal) {
        this.principal = principal;
    }

    public void setRecolectorDatos(RecolectorDatos recolectorDatos) {
        this.recolectorDatos = recolectorDatos;
    }

    public VistaSeleccionDiaEspecifico getSeleccionDiaEspecifico() {
        return seleccionDiaEspecifico;
    }

    public void setRespaldos(ArrayList<Respaldo> respaldos) {
        this.respaldos = respaldos;
    }

    public VistaSeleccionRespaldo() {
        initComponents();
        objXML = new XML();
        recolectorDatos = new RecolectorDatos();
        this.seleccionDiaAlMes = new VistaSeleccionDiaAlMes();
        seleccionDiaAlMes.setVista(this);
        seleccionDiaEspecifico = new VistaSeleccionDiaEspecifico();
        seleccionDiaEspecifico.setVista(this);
        this.defaultTableModel = new DefaultTableModel();
        defaultTableModel = (DefaultTableModel) tablaTablespaces.getModel();
        setVisible(false);
        setLocationRelativeTo(null);
        this.setResizable(false);
    }

    public void mostrarTablespaces(ArrayList<Tablespace> tablespaces, boolean ch) {
        tablaTablespaces.setVisible(true);
        if (defaultTableModel.getRowCount() > 0) {
            for (int i = defaultTableModel.getRowCount() - 1; i > -1; i--) {
                defaultTableModel.removeRow(i);
            }
        }
        for (Tablespace ind : tablespaces) {
            if (ch) {
                defaultTableModel.addRow(new Object[]{true, ind.getNombre()});
            } else {
                defaultTableModel.addRow(new Object[]{false, ind.getNombre()});
            }
        }
        tablaTablespaces.repaint();
        this.repaint();
    }

    public ArrayList<String> obtenerRespaldar() {

        ArrayList<String> nombres = new ArrayList<>();
        for (int i = defaultTableModel.getRowCount() - 1; i > -1; i--) {
            if ((boolean) defaultTableModel.getValueAt(i, 0)) {
                nombres.add((String) defaultTableModel.getValueAt(i, 1));
            }
        }
        return nombres;
    }

    public void recibeDia(int dia) {
        this.respaldos.add(new Respaldo(tipo, regularidad, qTables, tablespaces, String.valueOf(dia)));
        this.principal.agregarInfoRespaldos(respaldos);
        llamaXML();
    }

    public void recibeDia(String dia) {        
        this.respaldos.add(new Respaldo(tipo, regularidad, qTables, tablespaces, dia));
        this.principal.agregarInfoRespaldos(respaldos);
        llamaXML();
    }

    public void mostrarOpciones(ArrayList<Tablespace> tablespaces, int tipoRespaldo, int tipoSeleccion, int regularidad) {
        System.out.println("tiposele = " + tipoSeleccion);
        System.out.println("tipoFecha = " + regularidad);
        System.out.println("tiporespaldo = " + tipoRespaldo);
        this.tipo = tipoRespaldo;
        this.tablespaces = tablespaces;
        this.qTables = tipoSeleccion;
        this.regularidad = regularidad;
        if (tipoSeleccion == Respaldo.SELECCION) {
            mostrarTablespaces(tablespaces, false);
            setVisible(true);
        } else {
            String fecha = "";
            switch (regularidad) {
                case Respaldo.SEMANAL:
                    fecha = escogerDia();
                    this.respaldos.add(new Respaldo(tipo, regularidad, qTables, tablespaces, fecha));//yutyh
                    this.principal.agregarInfoRespaldos(respaldos);
                    llamaXML();
                    break;
                case Respaldo.MENSUAL:
                    this.seleccionDiaAlMes.mostrar();
                    break;
                case Respaldo.ESPECIFICO:
                    this.seleccionDiaEspecifico.mostrar();
                    System.out.println("Especifico");
                    break;
                default:
                    break;
            }
        }

    }

    public void llamaXML() {
        objXML.Escribir_XML_Respaldo(respaldos);
    }

    public String escogerDia() {
        Object[] selectionValues = {"Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"};
        String initialSelection = "Días";
        Object selection = JOptionPane.showInputDialog(null, "Que día de la semana desea realizar el respaldo",
                "¿Que día de la semana desea realizar el respaldo?", JOptionPane.QUESTION_MESSAGE, null, selectionValues, initialSelection);
        return (String) selection;
    }

    public ArrayList<Tablespace> obtenerTablespacesRepaldar() {
        ArrayList<Tablespace> resp = new ArrayList<>();
        ArrayList<String> nombre = obtenerRespaldar();
        for (String name : nombre) {
            for (Tablespace tb : tablespaces) {
                if (name.equals(tb.getNombre())) {
                    resp.add(tb);
                }
            }
        }
        return resp;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scroll = new javax.swing.JScrollPane();
        tablaTablespaces = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tablaTablespaces.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Respaldar", "Tablespace"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        scroll.setViewportView(tablaTablespaces);
        if (tablaTablespaces.getColumnModel().getColumnCount() > 0) {
            tablaTablespaces.getColumnModel().getColumn(0).setResizable(false);
            tablaTablespaces.getColumnModel().getColumn(1).setResizable(false);
        }

        jButton1.setText("Aceptar");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 181, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addComponent(scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked

        dispose();
        this.tablespaces = obtenerTablespacesRepaldar();
        String fecha;
        switch (regularidad) {
            case Respaldo.SEMANAL:
                fecha = escogerDia();
                this.respaldos.add(new Respaldo(tipo, regularidad, qTables, tablespaces, fecha));//ikjhbjk
                this.principal.agregarInfoRespaldos(respaldos);
                llamaXML();
                break;
            case Respaldo.MENSUAL:
                this.seleccionDiaAlMes.mostrar();
                break;
            case Respaldo.ESPECIFICO:
                this.seleccionDiaEspecifico.mostrar();
                System.out.println("Especifico");
                break;
            default:
                break;
        }

    }//GEN-LAST:event_jButton1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaSeleccionRespaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaSeleccionRespaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaSeleccionRespaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaSeleccionRespaldo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VistaSeleccionRespaldo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane scroll;
    private javax.swing.JTable tablaTablespaces;
    // End of variables declaration//GEN-END:variables
}
